package Servlet;

import Dao.Impl.KnowledgeBaseDAOImpl;
import Dao.Impl.KnowledgeBaseMemberDAOImpl;
import Dao.Impl.UserDAOImpl;
import Dao.KnowledgeBaseDAO;
import Dao.KnowledgeBaseMemberDAO;
import Dao.UserDAO;
import Dto.UserDto;
import Service.KnowledgeBaseService;
import Service.UserService;
import com.fasterxml.jackson.databind.ObjectMapper;
import entity.User;
import exception.BusinessException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONException;
import org.json.JSONObject;
import req.KnowledgeBaseRequest;
import utils.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author Su
 * @Date 2025/4/30 15:59
 * @Version 1.0 （版本号）
 */
@WebServlet("/api/user/profile")
public class UserProfileServlet extends HttpServlet {
    private UserService userService;
    private ObjectMapper objectMapper;

    @Override
    public void init() throws ServletException {
        try {
            Connection connection = DBUtil.getConnection();
            userService = new UserService(connection);
            this.objectMapper = new ObjectMapper();
        } catch (SQLException e) {
            throw new ServletException("初始化失败", e);
        }
    }

    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // 统一设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        JSONObject responseJson = new JSONObject();

        try {
            // 检查登录状态
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

            User user = (User) session.getAttribute("user");
            //查看用户详细信息
            User findUser = userService.findByUsername(user.getUsername());
            responseJson.put("code", 200);
            responseJson.put("message", "请求成功");
            responseJson.put("data", new JSONObject(objectMapper.writeValueAsString(findUser)));
        } catch (JSONException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "请求参数错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        // 统一设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        JSONObject responseJson = new JSONObject();

        try {
            // 检查登录状态
            HttpSession session = req.getSession(false);
            if (session == null) {
                responseJson.put("code", 401);
                responseJson.put("message", "未登录");
                resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
            User user = (User) session.getAttribute("user");
            // 配置上传参数
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            // 创建UserDto对象用于存储解析的数据
            UserDto userDto = new UserDto();

            // 解析请求的内容提取文件数据
            List<FileItem> formItems = upload.parseRequest(req);

                // 处理表单字段和文件
            if (formItems != null && formItems.size() > 0) {

                // 遍历表单项
                for (FileItem item : formItems) {
                    // 处理表单字段
                    if (item.isFormField()) {
                        String fieldName = item.getFieldName();
                        String fieldValue = item.getString("UTF-8");

                        // 根据字段名设置UserDto属性
                        switch (fieldName) {
                            case "userId":
                                userDto.setUserId(Integer.parseInt(fieldValue));
                                break;
                            case "username":
                                userDto.setUsername(fieldValue);
                                break;
                            case "password":
                                userDto.setPassword(fieldValue);
                                break;
                            case "email":
                                userDto.setEmail(fieldValue);
                                break;
                        }
                    } else {
                        // 处理文件
                        if ("file".equals(item.getFieldName()) && !item.getName().isEmpty()) {
                            // 获取文件名
                            // 为避免文件名冲突，添加时间戳
                            String fileExtension = item.getName().substring(item.getName().lastIndexOf("."));
                            // 生成唯一文件名
                            String fileName = "user_" + user.getUserId() + "_" + System.currentTimeMillis() + fileExtension;
                            // 创建上传目录
                            String uploadPath = "D:/研究生/舒琳的项目/feishu_project/uploads/avatar";
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }
                            String filePath = uploadPath + File.separator + fileName;
                            File storeFile = new File(filePath);
                            // 保存文件到硬盘
                            item.write(storeFile);
                            // 设置UserDto的avatar属性
                            userDto.setAvatarUrl("/avatar/" + fileName);
                        }
                    }
                }
//            UserDto updateUser = objectMapper.readValue(req.getReader(), UserDto.class);
//            User user = (User) session.getAttribute("user");
//            String url = "";
//            if (updateUser.getAvatar() != null && updateUser.getAvatar().length() > 0) {
//                //上传头像
//                url = handleAvatarUpload((Part)updateUser.getAvatar(),user.getUserId());
//            }
//            user.setAvatarUrl(url);
//            //更新用户信息
//            userService.updateUser(user);
            }
            userService.updateUser(userDto);
            responseJson.put("code", 200);
            responseJson.put("message", "修改成功");
        } catch (NumberFormatException e) {
            responseJson.put("code", 400);
            responseJson.put("message", "ID格式错误");
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        } catch (SQLException e) {
            responseJson.put("code", 500);
            responseJson.put("message", "系统内部错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } catch (Exception e) {
            responseJson.put("code", 500);
            responseJson.put("message", "处理请求时发生错误");
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            resp.getWriter().print(responseJson.toString());
        }
    }

}
